﻿#include "unrealircd.h"
CMD_FUNC(cmd_showUserMessage);
CMD_FUNC(cmd_showUserApplicant);
CMD_FUNC(cmd_SearchUser);
char * GetThirdName(ThirdAPPID app);
char * getAppTypeName(int appType);
char * getAppStatusName(int appstatus);

ModuleHeader MOD_HEADER
= {
	"third/showusermessage",
	"1.1",
	"This module will add, delete, change, check and other operations to the database",
	"waitch",
	"unrealircd-5",
};

MOD_INIT()
{
	CommandAdd(modinfo->handle, "SHOWUSERMESSAGE", cmd_showUserMessage, 1, CMD_USER);
	CommandAdd(modinfo->handle, "SHOWUSERAPPLICANT", cmd_showUserApplicant, 0, CMD_USER);
    CommandAdd(modinfo->handle, "SEARCHUSER", cmd_SearchUser, 1, CMD_USER);
	return MOD_SUCCESS;
}

MOD_LOAD()
{
	return MOD_SUCCESS;
}

MOD_UNLOAD()
{
	return MOD_SUCCESS;
}

/**
 * @brief 查询用户详细信息
 * parv[1] 用户名,可以为其他用户
 */
CMD_FUNC(cmd_showUserMessage){
    char * queryUserName = NULL;
    bool isSelf = false;
    if(parc == 2){
        if(BadPtr(parv[1])){
            sendnumeric(client, ERR_NEEDMOREPARAMS, "SHOWUSERMESSAGE");
            return ;
        }
        if(!strcasecmp(parv[1],"null")){
            isSelf = true;
            safe_strdup(queryUserName,client->user->username);
        }
        else if (!strcmp(parv[1],client->user->username)){
            isSelf = true;
            safe_strdup(queryUserName,client->user->username);
        }else{
            safe_strdup(queryUserName,parv[1]);
        }
    }
    else if(parc==1){
        isSelf = true;
        safe_strdup(queryUserName,client->user->username);
    }
    else{
        sendnumeric(client, ERR_NEEDMOREPARAMS, "SHOWUSERMESSAGE");
        return ;
    }
    int dataLen = 0;
    D_User * user_info = queryImUserByUserName(queryUserName,&dataLen);
    if(dataLen != 1){
        sendnumeric(client, QUERYMESSAGEFAILE);
        db_D_UserFree(user_info,dataLen);
        return;
    }
    cJSON * result_json = cJSON_CreateObject();

    if(isSelf){     //查询自己的信息，可以获得更多的信息数据
        if(user_info->tel){
            cJSON_AddStringToObject(result_json, "Tel",user_info->tel);
        }
        
        int userEmailLen = 0;
        D_im_user_email * userEmail = queryImUserEmailById(*(user_info->id),&userEmailLen);
        if(userEmailLen>0){
            cJSON *emailArray  = cJSON_CreateArray();
            for(int i=0;i<userEmailLen;++i){
                cJSON_AddStringToObject(emailArray,"",userEmail[i].email);
            }
            db_D_UserEmailFree(userEmail,userEmailLen);
            
            cJSON_AddItemToObject(result_json,"Email",emailArray);
        }


        char s_time[30];
		db_timestamp_to_string(user_info->created_at, s_time);
        cJSON_AddStringToObject(result_json, "Created_at",s_time);
        int third_len = 0;
        D_third_login * third_info= queryImThirdLoginByUserid(client->user_id,&third_len);
        if(third_len!=-1){
            cJSON *thirdArray  = cJSON_CreateArray();
            for(int i=0;i<third_len;i++){
                cJSON_AddStringToObject(thirdArray,"",GetThirdName(*(third_info[i].third_id)));
            }
            db_D_ThirdLoginFree(third_info,third_len);
            cJSON_AddItemToObject(result_json,"ThirdApp",thirdArray);
        }
        
    }
    cJSON_AddStringToObject(result_json, "UserName",user_info->user_name);
    cJSON_AddStringToObject(result_json, "UserNickName",user_info->user_nick);
    cJSON_AddNumberToObject(result_json, "UserId",(*user_info->id));
    sendnumeric(client, QUERYMESSAGESUCCESS,cJSON_PrintUnformatted(result_json));
    cJSON_Delete(result_json);

}

char * GetThirdName(ThirdAPPID app){
    switch(app){
        case THIRDAPPID_QQ:
            return "QQ";
        case THIRDAPPID_WECHAT:
            return "Wechat";
        default:
            return "UNKNOW";
    }
}


/**
 * @brief 显示用户所有的申请
 * 
 */
CMD_FUNC(cmd_showUserApplicant){
    cJSON * result_json = cJSON_CreateObject();
    int appLen=0;
    D_im_relation_applicant * applicants = queryImRelationApplicantByRespondentId(client->user_id,&appLen);
    cJSON *thirdArray  = cJSON_CreateArray();
    if(appLen>0){
        for(int i = 0; i < appLen; ++i){
            cJSON * appJson = cJSON_CreateObject();
            char *appTimep = safe_alloc(sizeof(char)*20);
            db_timestamp_to_string(applicants[i].applicant_time,appTimep);
            cJSON_AddStringToObject(appJson, "ApplicantTime",appTimep);
            cJSON_AddNumberToObject(appJson,"ApplicantId",*(applicants[i].relation_applicant_id));
            safe_free(appTimep);
            int appUserLength = 0;
            D_User *app_user = queryImUserById(*(applicants[i].applicant_id), &appUserLength);
            if(app_user){
                cJSON_AddNumberToObject(appJson,"ApplicantUserId",*(app_user->id));
                cJSON_AddStringToObject(appJson,"ApplicantUserName", app_user->user_name);
                cJSON_AddStringToObject(appJson,"ApplicantUserNick", app_user->user_nick);
                db_D_UserFree(app_user,appUserLength);
            }
            cJSON_AddStringToObject(appJson, "ApplicantType",getAppTypeName(*(applicants[i].applicant_type)));
            cJSON_AddStringToObject(appJson, "ApplicantStatus",getAppStatusName(*(applicants[i].applicant_status)));
            cJSON_AddItemToObject(thirdArray,"",appJson);
        } 
    }
    else{
        ircd_log(LOG_ERROR,"showUserApplicant faile rt=%d",appLen);
    }
    cJSON_AddItemToObject(result_json,"Applicants",thirdArray);
    sendnumeric(client, USERAPPLICANT,cJSON_PrintUnformatted(result_json));
    cJSON_Delete(result_json);
    db_D_imRelationApplicantFree(applicants,appLen);
}

char * getAppTypeName(int appType){
    switch(appType){
        case ADDFRIEND:
            return "add friends";
        case ADDGRPOUP:
            return "add group";
        case INVITEGROUP:
            return "invite group";
        default:
            return "unknow Type";
    }
}

char * getAppStatusName(int appstatus){
    switch(appstatus){
        case NOSELECT:
            return "not select";
        case AGREE:
            return "agree";
        case REFUSE:
            return "refuse";
        default:
            return "unknow status";
    }
}

/**
 * @brief 根据用户名/手机号/邮箱号搜索用户简单的信息
 * parv[1]: 用户名/手机号/邮箱号
 */
CMD_FUNC(cmd_SearchUser){
    if (parc != 2 || BadPtr(parv[1])) {
		sendnumeric(client, PARAMERROR, "ADDFRIEND","parv[1]");
		return;
	}
    int userByUserNameLength = 0;
    D_User * userByUserName = NULL;
    int userByTelLength = 0;
    D_User * userByTel = NULL;
    int userByEmailLength = 0;
    D_User * userByEmail = NULL;
    userByTel = queryImUserByTel(parv[1],&userByTelLength);
    userByUserName = queryImUserByUserName(parv[1],&userByUserNameLength);
    userByEmail = queryImUserByEmail(parv[1],&userByEmailLength);
    int flag = 0;
    D_User * users[3];
    if(userByTel){
        users[flag++] =userByTel;
    }
    if(userByUserName){
        users[flag++] =userByUserName;
    }
    if(userByEmail){
        users[flag++] =userByEmail;
    }
    cJSON * result_json = cJSON_CreateObject();
    cJSON *thirdArray  = cJSON_CreateArray();
    for(int i = 0; i < flag; ++i){
        int isUion = 1;
        for(int j = i+1; j < flag; ++j){
            if(*(users[i]->id)== *(users[j]->id)){
                isUion = 0;
                break;
            }
        }
        if(isUion){
            cJSON * appJson = cJSON_CreateObject();
            cJSON_AddNumberToObject(appJson,"UserId",*(users[i]->id));
            cJSON_AddStringToObject(appJson,"UserName", users[i]->user_name);
            cJSON_AddStringToObject(appJson,"UserNick", users[i]->user_nick);
            cJSON_AddItemToObject(thirdArray,"",appJson);
        }
    }
    cJSON_AddItemToObject(result_json,"searchUsers",thirdArray);
    sendnumeric(client, SEARCHUSERSUCCESS,cJSON_PrintUnformatted(result_json));
    cJSON_Delete(result_json);
    db_D_UserFree(userByUserName,userByUserNameLength);
    db_D_UserFree(userByTel,userByTelLength);
    db_D_UserFree(userByEmail,userByEmailLength);
}
